package com.dhecp.project.flowable.cmd;

import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName JumpTaskCommand
 * @Description 驳回/回退跳转命令
 * @Author alula
 * @Date 2019-12-09 9:58
 */
public class JumpTaskCommand  implements Command<ExecutionEntity> {
    protected RuntimeService runtimeService;
    private String procInstId;
    private String targetActivityId;
    private String deleteReason;

    public JumpTaskCommand(RuntimeService runtimeService, String procInstId, String targetActivityId, String deleteReason) {
        this.runtimeService = runtimeService;
        this.procInstId = procInstId;
        this.targetActivityId = targetActivityId;
        this.deleteReason = deleteReason;
    }

    @Override
    public ExecutionEntity execute(CommandContext commandContext) {
        ExecutionEntity executionEntity = CommandContextUtil.getExecutionEntityManager(commandContext).findByRootProcessInstanceId(procInstId);
        ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
        List<ExecutionEntity> executions = executionEntityManager.findChildExecutionsByProcessInstanceId(procInstId);
        List<String> executionIds = new ArrayList<>();
        executions.forEach(execution -> {
            executionIds.add(execution.getId());
            List<TaskEntity> taskLists = CommandContextUtil.getTaskService().findTasksByExecutionId(execution.getId());
            for (TaskEntity taskEntity : taskLists) {
                HistoricTaskInstanceEntity historicTaskInstance = CommandContextUtil.getDbSqlSession().selectById(HistoricTaskInstanceEntity.class,taskEntity.getId());
                if (historicTaskInstance != null) {
                    historicTaskInstance.markEnded(deleteReason, new Date());
                }
            }
        });
        runtimeService.createChangeActivityStateBuilder().moveExecutionsToSingleActivityId(executionIds, targetActivityId).changeState();
        return executionEntity;
    }
}
